#! /usr/bin/perl -w
#
# Creates the $GENIE/src/Conventions/GVersion.h header file
#
# C.Andreopoulos <constantinos.andreopoulos \at cern.ch>, Rutherford Lab.
#
# Revised for usage with git by S. Gardiner <gardiner \at fnal.gov>, Fermilab.

$GENIE = $ENV{'GENIE'};
die ("Not even the GENIE environmental variable is defined!") unless defined $GENIE;

# Read version info
open(REL_INFO, "<$GENIE/VERSION") or die("Can not read the GENIE release information!");
@rel_info=<REL_INFO>;
close(REL_INFO);
chomp($release = $rel_info[0]);

# ($major, $minor, $rev) = split('.', $release);
# note: split() doesn't split on dots...
$release=~m/(\d+).(\d+).(\d+)/;
$major = $1;
$minor = $2;
$revis = $3;

# Get the hash of the current git commit
$git_revision = `git rev-parse --verify HEAD`;
if ($?) {
  # Couldn't run git rev-parse
  # This may be a user without git who installs GENIE from a tarball.
  # Try to extract the hash from $GENIE/.git/HEAD
  $git_revision = "-1";
  if (open(GIT_HEAD, "<$GENIE/.git/HEAD")) {
    @git_head_hash = <GIT_HEAD>;
    close(GIT_HEAD);
    # If we have a reference listed in the file instead
    # of a hash, drop the leading "ref:" and get the
    # hash from the listed file
    if ( substr($git_head_hash[0], 0, 4) eq "ref:") {
      $temp_ref = substr($git_head_hash[0], 4);
      $temp_ref =~ s/^\s+|\s+$//g; # Remove all whitespace from temp_ref
      $git_revision = `cat $GENIE/.git/$temp_ref`;
    }
    # Otherwise, get the hash from $GENIE/.git/HEAD
    else {
      $git_revision = $git_head_hash[0];
    }
  }
}
chomp($git_revision);

# Open header file
$GVRS_FILE = "$GENIE/src/Framework/Conventions/GVersion.h";
open(GVRS, ">$GVRS_FILE") or die("Can not write out the GVersion.h file!");

# Write header file
print GVRS "#ifndef _GVERSION_H_ \n";
print GVRS "#define _GVERSION_H_ \n";
print GVRS "/* \n";
print GVRS " * Version information automatically generated by the GENIE installer \n";
print GVRS " * \n";
print GVRS " * These macros can be used in the following way (as the ones at ROOT's RVersion.h): \n";
print GVRS " * #if __GENIE_RELEASE_CODE__ >= GRELCODE(2,4,11) \n";
print GVRS " * #include <newheader.h>\n";
print GVRS " * #else\n";
print GVRS " * #include <oldheader.h>\n";
print GVRS " * #endif\n";
print GVRS "*/ \n\n";
print GVRS "#define GRELCODE(a,b,c) (((a) << 16) + ((b) << 8) + (c)) \n\n";
print GVRS "#define __GENIE_RELEASE__      \"$release\"\n";
print GVRS "#define __GENIE_RELEASE_CODE__ GRELCODE($major,$minor,$revis) \n\n";

# print the commit number even if it is unresolved (-1) -> that flags that it is unresolved...
print GVRS "#define __GENIE_GIT_REVISION__ \"$git_revision\" \n\n";

if($major == 999 && $minor == 999 && $revis == 999) {
  print GVRS "#define __GENIE_DEVEL_VERSION__ \n\n";
}
else {
  if($minor % 2) {
     print GVRS "#define __GENIE_RELEASE_CANDIDATE__ \n\n";
  }
}

print GVRS "#endif\n\n";

# Close header file
close(GVRS);
